﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using HOPU.OnlineSchool.Core;
using Microsoft.AspNetCore.Http;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace HOPU.OnlineSchool.Application.Npoi.Service
{
    public class NpoiService: INpoiService, ITransient
    {
        private readonly IRepository<EduSubject> _subjectRepository;

        public NpoiService(IRepository<EduSubject> subjectRepository)
        {
            this._subjectRepository = subjectRepository;
        }
        /// <summary>
        /// 批量导入课程分类数据
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public async Task<string> SubjectImportsync(IFormFile file)
        {
            using (var fs = file.OpenReadStream())
            {
                //创建工作簿
                IWorkbook workbook = WorkbookFactory.Create(fs);

                //得到工作簿中的第一个sheet
                var sheet = workbook.GetSheetAt(0);

                //获取工作簿中的总数据数（行数）
                int rowCount = sheet.LastRowNum;

                //定义一个待导入数据的集合
                var importList = new List<EduSubject>();

                //循环遍历当前sheet的行(含有数据的行)
                for (int i = 1; i <= rowCount; i++)
                {
                    var row = sheet.GetRow(i);

                    var subject = new EduSubject();

                    //获取当前行的第一个单元格的数据
                    subject.Title = row.GetCell(0).StringCellValue;
                    subject.Id = YitIdHelper.NextId().ToString();
                    subject.ParentId = "0";
                    importList.Add(subject);

                    //获取当前行的第二个单元格的数据
                    var subject2 = new EduSubject();
                    subject2.Title = row.GetCell(1).StringCellValue;
                    subject2.Id = YitIdHelper.NextId().ToString();

                    //二级分类的父id为一级分类的主键id
                    subject2.ParentId = subject.Id;
                    importList.Add(subject2);


                    //循环里面进行添加？坚决不能！！！
                }

                await _subjectRepository.InsertAsync(importList);
            }

            return "导入成功";
        }
    }
}
